package com.mk.legoscans2.data;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.mk.legoscans2.Utils;

import android.sax.EndTextElementListener;
import android.sax.RootElement;

public class ApiFavoritesRepository extends SaxFeedParser implements FavoritesRepository {

	String _account;
	String _domain;
	int _port;
	
	public ApiFavoritesRepository(String account, String domain, int port){
		_account = account;
		_domain = domain;
		_port = port;
	}
	
	public List<String> getFavorites() {
		final List<String> favorites = new ArrayList<String>();
		
		RootElement root = new RootElement("Favorites");
		root.getChild("string").setEndTextElementListener(new EndTextElementListener() {
			public void end(String body) {
				favorites.add(body);
			}
		});

		URL url;
		try {
			URI uri = new URI("http", null, _domain, _port, "/favorites/xml/" + _account, "source=android", null);
			url = new URL(uri.toASCIIString());
		} catch (URISyntaxException e) {
			throw new RuntimeException(e);
		} catch (MalformedURLException e) {
			throw new RuntimeException(e);
		}
		
		ExecuteParser(url, root);
		
		return favorites;
	}

	public boolean toggleFavorite(String scanId) {
		String response = Utils.postToWebApi("/togglefavorite/json/" + _account, "source=android&scanid=" + scanId);
		return Boolean.parseBoolean(response);
	}

	public boolean isFavorite(String scanId) {
		List<String> favorites = getFavorites();
		for (String fav : favorites) {
			if(scanId.equals(fav))
				return true;
		}
		
		return false;
	}
}
